from django.contrib import admin
from .models import *
from .forms import *
# import django.apps
from decimal import Decimal
from openpyxl import Workbook
from django.http import HttpResponse


#导出功能
class ExportExcelMixin(object):
    def export_as_excel(self, request, queryset):
        meta = self.model._meta
        field_names = [field.name for field in meta.fields]
        response = HttpResponse(content_type='application/msexcel')
        response['Content-Disposition'] = f'attachment; filename={meta}.xlsx'
        wb = Workbook()
        ws = wb.active
        ws.append(field_names)
        for obj in queryset:
            for field in field_names:
                data = [f'{getattr(obj, field)}' for field in field_names]
            row = ws.append(data)
        wb.save(response)
        return response

    export_as_excel.short_description = '导出Excel'

    # def inport_by_excel(self, request, queryset):
    #     return "导入失败---该功能未实现"

    # inport_by_excel.short_description = '从Excel导入'


# # link 功能
# class BMRmodelLink(admin.StackedInline):
#     model = BMRsubModel
#     extra = 0


# 患者入组+基本资料
@admin.register(InPatientsModel)
class InPatientsAdmin(admin.ModelAdmin, ExportExcelMixin):
    form = InPatientsForm
    myList = []
    reList = []
    fs = InPatientsModel._meta.get_fields()
    for f in fs:
        if f.name.__contains__("_related") == False and f.name != 'id':
            myList.append(f.name)
    for f in fs:
        if f.name.__contains__("_related") == True:
            myList.append('count' + f.name)
    list_display = myList
    fieldsets = (
        ("一、基本资料", {
            'fields': ('姓名', '住院号', '病区', '床号', '诊断', '年龄', '性别', '电话', '入院日期', '管组教授', '手术日期', '入组日期')
        }),
        ("二、入组资料", {
            'fields': ('ECOG评分', 'GLIM诊断', '饮水吞咽试验', '饮食习惯', '体重下降', '进食量减少', '干预方式', 'ONS', '膳食总结', '血糖正常', '营养缺乏症状')
        }),
        ("三、出组资料", {
            'fields': ('出院状态', '出院体重', '出院营养状况描述')
        }),
        (None, {
            'fields': ('操作者', '更新时间')
        }),
    )
    # inlines = [BMRmodelLink]
    list_filter = ['性别', '管组教授', '出院状态', '诊断']
    search_fields = ['姓名', '住院号']
    list_per_page = 25
    list_display_links = [
        '姓名',
        '住院号',
    ]
    actions = ['export_as_excel', "inport_by_excel"]

    def save_model(self, request, obj, form, change):
        if obj.操作者 == None:
            obj.操作者 = str(request.user)
        obj.save()


# 2.NRS营养风险筛查
@admin.register(LaboratoryAccessModel)
class LaboratoryAccessAdmin(admin.ModelAdmin, ExportExcelMixin):
    fs = LaboratoryAccessModel._meta.get_fields()
    myList = []
    for f in fs:
        if f.name.__contains__("_related") == False and f.name != 'id':
            myList.append(f.name)
    list_display = myList
    list_filter = ['评估人']
    search_fields = ['患者__姓名', '患者__住院号']
    actions = ['export_as_excel']

    def save_model(self, request, obj, form, change):

        if obj.评估人 == None:
            obj.评估人 = str(request.user)
        obj.save()


# 2.人体成分
@admin.register(BodyCompositionModel)
class BodyCompositionAdmin(admin.ModelAdmin, ExportExcelMixin):
    fs = BodyCompositionModel._meta.get_fields()
    myList = []
    for f in fs:
        if f.name.__contains__("_related") == False and f.name != 'id':
            myList.append(f.name)
    list_display = myList
    readonly_fields = ['BMI', "体脂率"]
    list_filter = ['性别', '评估人']
    search_fields = ['患者__姓名', '患者__住院号']
    actions = ['export_as_excel']

    def save_model(self, request, obj, form, change):
        #重写数据保存操作
        if obj.身高 != None and obj.身高 != 0 and obj.体重 != None:
            #BMI
            num = round(obj.体重 / ((obj.身高 / 100)**2), 3)
            if num > 100 or num < 1:
                obj.BMI = "体重或身高录入有误"
            else:
                obj.BMI = str(num)
        if obj.BMI != "体重或身高录入有误" and obj.年龄 != None and obj.性别 != None:
            # 体脂率
            obj.体脂率 = str(round(Decimal(1.2) * num + Decimal(0.23) * obj.年龄 - Decimal(10.8) * obj.性别 - Decimal(5.4), 3))
        if obj.评估人 == None:
            obj.评估人 = str(request.user)
        obj.save()


# 3.基础代谢率
@admin.register(BMRModel)
class BMRAdmin(admin.ModelAdmin, ExportExcelMixin):
    fs = BMRModel._meta.get_fields()
    myList = []
    for f in fs:
        if f.name.__contains__("_related") == False and f.name != 'id':
            myList.append(f.name)
    list_display = myList
    readonly_fields = ['基础代谢率']
    list_filter = ['评估人']
    search_fields = ['患者__姓名', '患者__住院号']
    actions = ['export_as_excel']

    def save_model(self, request, obj, form, change):
        #重写数据保存操作
        if obj.收缩压 != None and obj.舒张压 != None and obj.脉搏数 != None:
            obj.基础代谢率 = str(round((obj.收缩压 - obj.舒张压) + obj.脉搏数 - 111, 0))
        if obj.评估人 == None:
            obj.评估人 = str(request.user)
        obj.save()


# 4.肠内营养耐受
@admin.register(NutrtionToleranceModel)
class NutrtionToleranceAdmin(admin.ModelAdmin, ExportExcelMixin):
    form = NutrtionToleranceForm
    fs = NutrtionToleranceModel._meta.get_fields()
    myList = []
    for f in fs:
        if f.name.__contains__("_related") == False and f.name != 'id':
            myList.append(f.name)
    list_display = myList
    readonly_fields = ['肠内营养耐受得分']
    list_filter = ['评估人']
    search_fields = ['患者__姓名', '患者__住院号']
    actions = ['export_as_excel']

    def save_model(self, request, obj, form, change):
        #重写数据保存操作
        if obj.腹痛腹胀 != None and obj.恶心呕吐 != None and obj.腹泻 != None:
            obj.肠内营养耐受得分 = obj.腹痛腹胀 + obj.恶心呕吐 + obj.腹泻
        if obj.评估人 == None:
            obj.评估人 = str(request.user)
        obj.save()


# 5.NRS营养风险筛查
@admin.register(NrsModel)
class NrsAdmin(admin.ModelAdmin, ExportExcelMixin):
    fs = NrsModel._meta.get_fields()
    myList = []
    for f in fs:
        if f.name.__contains__("_related") == False and f.name != 'id':
            myList.append(f.name)
    list_display = myList
    readonly_fields = ['NRS得分']
    list_filter = ['评估人']
    search_fields = ['患者__姓名', '患者__住院号']
    actions = ['export_as_excel']

    def save_model(self, request, obj, form, change):
        if obj.疾病严重程度 != None and obj.营养受损状况 != None and obj.年龄 != None:
            obj.NRS得分 = obj.疾病严重程度 + obj.营养受损状况 + obj.年龄
        if obj.评估人 == None:
            obj.评估人 = str(request.user)
        obj.save()
